package com.dgf.myboot.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.dgf.myboot.core.result.Result;
import com.dgf.myboot.core.result.ResultCode;
import com.dgf.myboot.core.service.ServiceException;

@RestControllerAdvice
public class GlobalExceptionHandler {

	private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	/**
	 * 业务异常
	 * @param request
	 * @param response
	 * @param e
	 * @return
	 */
	@ExceptionHandler(ServiceException.class)
	public Result serviceExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e){
		
		logger.info(e.getMessage());
		
		return new Result()
				.setCode(ResultCode.FAIL)
				.setMessage(e.getMessage());
	}
	
	@ExceptionHandler(NoHandlerFoundException.class)
    public Object noHandlerFoundErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
		logger.error(e.getMessage(),e);
		
		return new Result()
				.setCode(ResultCode.NOT_FOUND)
				.setMessage("接口[" + request.getRequestURI() + "] 不存在");
    }
	
	@ExceptionHandler(Exception.class)
    public Object defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
		logger.error(e.getMessage(),e);
		
		return new Result()
				.setCode(ResultCode.NOT_FOUND)
				.setMessage(e.getMessage());
    }
}
